#include "menu.h"
#include "ui_menu.h"

menu::menu(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::menu)
{
    ui->setupUi(this);
    init();
}

menu::~menu()
{
    delete ui;
}

void menu::init()
{
    tcpser=new QTcpServer(this);
    tcp_ve.resize(4);
    people_button.resize(4);
    isshow.resize(4,false);
    widgets.resize(4,nullptr);
    for(int i=0;i<4;i++)
    {
        QToolButton* tb=new QToolButton(this);
        people_button[i].second=tb;
        tb->setText(people_name[i]);
        QString s=QString::asprintf(":/%d.jpg",i+1);
        tb->setIcon(QPixmap(s));
        tb->setIconSize(QSize(120,60));
        people_button.push_back({i,tb});
        ui->verticalLayout_2->addWidget(tb);
        connect(tb,&QToolButton::clicked,this,[=](){
            if(isshow[i]==false)
            {
                isshow[i]=true;
                widgets[i]=new widget(people_name[i]);
                people_enter.insert(people_name[i]);
                //当用户界面退出时
                connect(widgets[i],&widget::closeWidget,this,[&](){

                    isshow[i]=false;
                    qDebug()<<people_name[i]<<"exit";
                    if(people_enter.find(people_name[i])!=people_enter.end())
                    people_enter.erase(people_enter.find(people_name[i]));
                    // delete widgets[i];
                    // widgets[i]=nullptr;
                });
                widgets[i]->show();
            }
        });
    }
    //新连接到来时
    connect(tcpser,&QTcpServer::newConnection,this,&menu::do_newConnect);
    tcpser->listen(QHostAddress::Any,8081);

}

void menu::do_newConnect()
{
   QTcpSocket* tcpsock=tcpser->nextPendingConnection();

   QString str;
   for(auto&e:people_enter)
       str+=e+" ";
   str.sliced(0,str.size()-1);
   tcpsock->write(QString("people "+str).toUtf8());

   //接收消息，并将此信息发送给所有与其相连的用户
    connect(tcpsock,&QTcpSocket::readyRead,this,[=](){

       QByteArray str=tcpsock->readAll();
        for(int i=0;i<tcp_ve.size();i++)
        {
            if(tcp_ve[i]==nullptr)
                continue;

            tcp_ve[i]->write(str.data());
        }
    });
    tcp_ve.push_back(tcpsock);

    //断开连接
    connect(tcpsock,&QTcpSocket::disconnected,this,[&](){

        auto item=tcp_ve.begin();
        while(item!=tcp_ve.end())
        {
            if(*item==tcpsock)
            {
                tcp_ve.erase(item);
                break;
            }
            ++item;
        }

    });

}

